package com.xmmj.baselibrary.base.activity.swipeback

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import java.util.*

class ActivityLifecycleHelper : ActivityLifecycleCallbacks {

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        addActivity(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        activities!!.remove(activity)
        if (activities!!.size == 0) {
            activities = null
        }
    }

    /**
     * 添加Activity到堆栈
     */
    private fun addActivity(activity: Activity) {
        if (activities == null) {
            activities = LinkedList()
        }
        activities!!.add(activity)
    }

    companion object {
        private var activities: MutableList<Activity>? = LinkedList()

        /**
         * 获取最后一个Activity
         */
        val latestActivity: Activity?
            get() {
                val count = activities!!.size
                return if (count == 0) {
                    null
                } else activities!![count - 1]
            }

        /**
         * 获取上一个Activity
         */
        val previousActivity: Activity?
            get() {
                val count = activities!!.size
                return if (count < 2) {
                    null
                } else activities!![count - 2]
            }
    }
}